﻿Imports System.Data
Imports CrystalDecisions.Shared
Imports CrystalDecisions.CrystalReports.Engine
Imports System.Data.OleDb
Imports System
Imports System.Globalization

Partial Class Interfaz_frmAdminFacturaIngresar
    Inherits System.Web.UI.Page
    Dim OT As String
    Dim CL As New ControladorLogica
    Dim dtDatos As New DataTable
    Dim dataset As New DataSet

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If CL.visibilidadesFormsInternos("Administracion", Session("user").ToString) = False Then
            Response.Redirect("Index.aspx")
        End If
        Dim ArrayItem As New ArrayList
        Dim ArrayOrdenCompra As New ArrayList
        Dim ArrayGuiaDespacho As New ArrayList
        Dim ArrayProveedor As New ArrayList
        Dim i As Integer

        ArrayItem = CL.ObtenerMaterial()
        ArrayOrdenCompra = CL.ObtenerOrdenCompra()
        ArrayGuiaDespacho = CL.obtenerGuiaDespacho()
        ArrayProveedor = CL.ObtenerProveedor()

        If Not Page.IsPostBack Then
            For i = 0 To ArrayItem.Count - 1
                Me.DropItemIF.Items.Add(DirectCast(ArrayItem.Item(i), Material).Nombre)
            Next

            For i = 0 To ArrayOrdenCompra.Count - 1
                Me.DropOrdenCompraIF.Items.Add(DirectCast(ArrayOrdenCompra.Item(i), OrdenCompra).NumeroDeOrden)
            Next

            For i = 0 To ArrayGuiaDespacho.Count - 1
                Me.DropGuiaDespachoIF.Items.Add(DirectCast(ArrayGuiaDespacho.Item(i), GuiaDespacho).Id)
            Next

            For i = 0 To ArrayProveedor.Count - 1
                Dim item As New ListItem
                item.Text = DirectCast(ArrayProveedor.Item(i), Proveedor).Rznsocial
                item.Value = DirectCast(ArrayProveedor.Item(i), Proveedor).Rut
                Me.DropProveedor.Items.Add(item)
            Next
        End If
        'se guardan datos en secion para el positback de la pagina respecto al los datos del datagridview
        If Session("IngresaFactura") Is Nothing Then
            Session("IngresaFactura") = dtDatos
        Else
            dtDatos = DirectCast(Session("IngresaFactura"), DataTable)

        End If

        If Not Page.IsPostBack Then
            Try
                dtDatos.Columns.Add(New DataColumn("ITEM"))
                dtDatos.Columns.Add(New DataColumn("CODIGO"))
                dtDatos.Columns.Add(New DataColumn("DETALLE"))
                dtDatos.Columns.Add(New DataColumn("CANTIDAD"))
                dtDatos.Columns.Add(New DataColumn("PRECIOUNITARIO"))

                Me.GridFacturaRecibida.DataBind()
                Me.GridFacturaRecibida.DataSource = Me.dtDatos

            Catch
            End Try
        End If


        'Me.GridFacturaRecibida.DataBind()
        Me.GridFacturaRecibida.DataSource = Me.dtDatos
        Me.onIngresarFactura()
        'Visualizador.Attributes.Add("onclick", "javascript:visualizadorFacturaRecibida();")
    End Sub

#Region "Botones"

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        llenaDatosProveedor()
    End Sub

    Protected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button4.Click
        IngresarItem()
    End Sub

    Protected Sub Button5_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button5.Click
        LimpiarTodoFacturaRecibida()
    End Sub

    Protected Sub Button6_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button6.Click
        IngresaFacturaBD()
        Me.vaciaGrid()
    End Sub

#End Region
  
#Region "Funcionalidades"
    Public Sub Mensaje(ByVal msg As String)
        Dim alertScript As String = "<script language=JavaScript runat=server>"
        alertScript &= "alert('" & msg & "');"
        alertScript &= "</script>"
        ClientScript.RegisterClientScriptBlock(Page.GetType(), "clientScrip", alertScript)
    End Sub

    Private Sub vaciaGrid()
        dtDatos = DirectCast(Session("EmiteFactura"), DataTable)
        If Not dtDatos Is Nothing Then
            dtDatos.Clear()
            Session("EmiteFactura") = dtDatos
        End If
    End Sub

    Public Sub offIngresarFactura()
        Me.PanelIngresarFact.Visible = False
    End Sub

    Public Sub onIngresarFactura()
        Me.PanelIngresarFact.Visible = True
    End Sub

    Private Sub IngresarItem()
        Try
            Dim drDatos As DataRow = dtDatos.NewRow

            If Me.TxTCodigoIF.Text <> "" And Me.TxTDetalleIF.Text <> _
            "" And Me.TxTCantidadIF.Text <> "" And Me.TxTPrecioUnitarioIF.Text <> "" Then

                drDatos.Item("ITEM") = Me.DropItemIF.Text
                drDatos.Item("CODIGO") = Me.TxTCodigoIF.Text
                drDatos.Item("DETALLE") = Me.TxTDetalleIF.Text
                drDatos.Item("CANTIDAD") = Me.TxTCantidadIF.Text
                drDatos.Item("PRECIOUNITARIO") = CInt(Me.TxTPrecioUnitarioIF.Text)

                dtDatos.Rows.Add(drDatos)

                Me.GridFacturaRecibida.DataSource = dtDatos
                Me.GridFacturaRecibida.DataBind()

                Me.LimpiarItemFacturaRecibida()
                Me.GridFacturaRecibida.ForeColor = Drawing.Color.Blue
                Me.LabelAviso.Text = "Los datos han sido ingresados satisfactoriamente"
            Else
                Me.LabelAviso.ForeColor = Drawing.Color.Red
                Me.LabelAviso.Text = "Complete todos los datos"
            End If

        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try
    End Sub

    Private Sub LimpiarTodoFacturaRecibida()
        LimpiarItemFacturaRecibida()
        TxtDireccionIF.Text = String.Empty
        TxTRutIF.Text = String.Empty
        TxTfonoIF.Text = String.Empty
        TxTGiroIF.Text = String.Empty
        TxTComunaIF.Text = String.Empty
        TxTCiudadIF.Text = String.Empty
    End Sub

    Private Sub LimpiarItemFacturaRecibida()
        TxTCodigoIF.Text = String.Empty
        TxTDetalleIF.Text = String.Empty
        TxTCantidadIF.Text = String.Empty
        TxTPrecioUnitarioIF.Text = String.Empty
        TxTVendedorIF.Text = String.Empty
        TxTCondVentaIF.Text = String.Empty
    End Sub

    Private Sub llenaDatosProveedor()
        Dim query As String = ""
        Dim dato As String = ""

        query = "select rut from proveedor where rznsocial='" + DropProveedor.SelectedValue + "'"
        dato = CL.Ejecuta(query).Item("rut")
        query = "select * from proveedor where rut='" + dato + "'"
        Dim ArrayProveedor As ArrayList = CL.ObtenerProveedor(query)

        TxTfonoIF.Text = DirectCast(ArrayProveedor.Item(0), Proveedor).Telefono
        TxtDireccionIF.Text = DirectCast(ArrayProveedor.Item(0), Proveedor).Direccion
        TxTRutIF.Text = DirectCast(ArrayProveedor.Item(0), Proveedor).Rut
        TxTGiroIF.Text = DirectCast(ArrayProveedor.Item(0), Proveedor).Giro
        TxTComunaIF.Text = DirectCast(ArrayProveedor.Item(0), Proveedor).Comuna
        TxTCiudadIF.Text = DirectCast(ArrayProveedor.Item(0), Proveedor).Ciudad
    End Sub

    Private Sub IngresaFacturaBD()
        Dim filaGrid As GridViewRow

        'Datos Fijos
        Dim proveedor As Proveedor = DirectCast(CL.ObtenerProveedorID(DropProveedor.SelectedValue).Item(0), Proveedor)
        Dim Fecha As String = BasicDatePicker2.Text
        Dim dia As String = Fecha.Substring(0, 2)
        Dim mes As String = Fecha.Substring(3, 2)
        Dim año As String = Fecha.Substring(6, 4)
        Dim iva As Integer = 0
        Dim TotalNeto As Integer = 0
        Dim TotalBruto As Integer = 0
        Dim TotalPorItem As Integer = 0
        Dim rznSocial As String = ""
        Dim direccion As String = ""
        Dim giro As String = ""
        Dim rut As String = ""
        Dim comuna As String = ""
        Dim telefono As String = ""
        Dim guiaDespacho As String = ""
        Dim vendedor As String = ""
        Dim ordenCompra As String = ""
        Dim condVenta As String = ""
        'Detalle de items
        Dim factItem As String = ""
        Dim facCodigo As String = ""
        Dim factDetalle As String = ""
        Dim factCantidad As String = ""
        Dim factPrecioUnitario As String = ""
        'Declaraciones para insert a BD
        Dim ArrayItemFactura As New ArrayList

        Try

            'Carga De Datos del Destinatario
            rznSocial = proveedor.Rznsocial
            direccion = proveedor.Direccion
            giro = proveedor.Giro
            rut = proveedor.Rut
            comuna = proveedor.Comuna
            telefono = proveedor.Telefono
            guiaDespacho = DropGuiaDespachoIF.Text
            vendedor = TxTVendedorIF.Text
            ordenCompra = DropOrdenCompraIF.Text
            condVenta = TxTCondVentaIF.Text

            'Suma Valores de actividades
            With Me.GridFacturaRecibida
                ' Recorrer las filas del dataGridView  
                For fila As Integer = 0 To .Rows.Count - 1
                    filaGrid = Me.GridFacturaRecibida.Rows(fila)
                    'Recorrer la cantidad de columnas que contiene el dataGridView  
                    factItem = filaGrid.Cells(1).Text
                    facCodigo = filaGrid.Cells(2).Text
                    factDetalle = filaGrid.Cells(3).Text
                    factCantidad = filaGrid.Cells(4).Text
                    factPrecioUnitario = filaGrid.Cells(5).Text

                    TotalPorItem = CInt(filaGrid.Cells(4).Text) * CInt(filaGrid.Cells(5).Text)
                    TotalNeto = TotalNeto + TotalPorItem

                    Dim itemFactura As New Item(filaGrid.Cells(2).Text, filaGrid.Cells(3).Text, filaGrid.Cells(4).Text, filaGrid.Cells(5).Text, _
                                                filaGrid.Cells(1).Text, CInt(filaGrid.Cells(5).Text) * 0.19, filaGrid.Cells(5).Text)
                    ArrayItemFactura.Add(itemFactura)
                Next fila
            End With


            'Calculo Valores Neto - Bruto - Iva
            iva = TotalNeto * 0.19
            TotalBruto = TotalNeto + iva

            'Creacion factura e Ingreso a la BD
            Dim nuevaFactura As New FacturaRecibida()
            nuevaFactura.ArrayItem = ArrayItemFactura
            nuevaFactura.CondVenta = TxTCondVentaIF.Text
            nuevaFactura.Fecha = Fecha
            nuevaFactura.ID = ""
            nuevaFactura.Iva = iva
            nuevaFactura.Neto = TotalNeto
            nuevaFactura.RefProveedor = proveedor
            nuevaFactura.RefOrdenCompra = DirectCast(CL.ObtenerOrdenCompraID(DropOrdenCompraIF.Text).Item(0), OrdenCompra)
            nuevaFactura.Total = TotalBruto

            CL.InsertarFactura(nuevaFactura)
        Catch ex As Exception
            Me.Mensaje(ex.ToString)
        End Try

    End Sub

#End Region

#Region "Eventos"
    'Grid Material
    Protected Sub GridFacturaRecibida_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
        GridFacturaRecibida.PageIndex = e.NewPageIndex
        'Bind data to the GridView control.
        GridFacturaRecibida.DataSource = Session("IngresaFactura")
        GridFacturaRecibida.DataBind()
    End Sub

    Protected Sub GridFacturaRecibida_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
        'Set the edit index.
        GridFacturaRecibida.EditIndex = e.NewEditIndex
        'Bind data to the GridView control.
        GridFacturaRecibida.DataSource = Session("IngresaFactura")
        GridFacturaRecibida.DataBind()
    End Sub

    Protected Sub GridFacturaRecibida_RowCancelingEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
        'Reset the edit index.
        GridFacturaRecibida.EditIndex = -1
        'Bind data to the GridView control.
        GridFacturaRecibida.DataSource = Session("IngresaFactura")
        GridFacturaRecibida.DataBind()
    End Sub

    Protected Sub GridFacturaRecibida_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
        'Retrieve the table from the session object.
        Dim dt As DataTable = CType(Session("IngresaFactura"), DataTable)

        'Update the values.
        Dim row As GridViewRow = GridFacturaRecibida.Rows(e.RowIndex)
        'Dim actividad As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text.ToString
        Dim CODIGO As String = (CType((row.Cells(2).Controls(0)), TextBox)).Text
        Dim DETALLE As String = (CType((row.Cells(3).Controls(0)), TextBox)).Text
        Dim CANTIDAD As String = (CType((row.Cells(4).Controls(0)), TextBox)).Text
        Dim PRECIOUNITARIO As String = (CType((row.Cells(5).Controls(0)), TextBox)).Text

        'dt.Rows(row.DataItemIndex)("ITEM") = actividad
        dt.Rows(row.DataItemIndex)("CODIGO") = CODIGO
        dt.Rows(row.DataItemIndex)("DETALLE") = DETALLE
        dt.Rows(row.DataItemIndex)("CANTIDAD") = CANTIDAD
        dt.Rows(row.DataItemIndex)("PRECIOUNITARIO") = PRECIOUNITARIO

        'Reset the edit index.
        GridFacturaRecibida.EditIndex = -1

        'Bind data to the GridView control.
        GridFacturaRecibida.DataSource = Session("IngresaFactura")
        GridFacturaRecibida.DataBind()
    End Sub

    Sub GridFacturaRecibida_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
        Dim dt As DataTable = CType(Session("IngresaFactura"), DataTable)
        dt.Rows(e.RowIndex).Delete()
        GridFacturaRecibida.DataSource = dt
        GridFacturaRecibida.DataBind()
    End Sub
#End Region


    
End Class
